# -*- coding: UTF-8 -*-
# *******************************************************************
# File Name: general_img
# > Author: 04000387
# > Created Time: 2025/1/6 14:24
# *******************************************************************
from pathlib import Path
import json


def load_img(_base_path):
    _base_path = Path(_base_path)
    _img_folder = "train_full_images_"
    _children = ["0", "1"]
    _img_dict = dict()
    for _it in _children:
        _img_folder_item = _base_path / (_img_folder + _it)

        for _img_path in _img_folder_item.iterdir():
            _name = _img_path.stem
            _img_dict[_name] = _img_path

    return _img_dict


def generate_general_image(img_path, out_path="../generate/text", _num=-1):
    """

    :param out_path: 输出路径
    :param img_path: "E:\\01_git\\generate_dir\\test"
    :return:
    """
    img_path = Path(img_path)
    img_dict = load_img(img_path)

    path = img_path / "train_full_labels.json"
    fp = open(path, "r", encoding="utf-8")

    res = json.load(fp)

    out_path = Path(out_path)
    jsonl_path = out_path / "real_world.jsonl"

    fp1 = open(jsonl_path, "w")

    item_list = []

    for i, img_stem in enumerate(res, start=1):
        if img_stem not in img_dict:
            continue

        img_path = img_dict[img_stem].absolute()

        patch_list = []
        for patch in res[img_stem]:
            patch_text = patch["transcription"]
            if patch_text == "###":
                continue

            patch_list.append(patch_text)

        string = "这是一张带有文字的图片,图片中的文字如下:" + "\n".join(patch_list)
        one = json.dumps({"img_file": str(img_path), "content": string}) + "\n"

        item_list.append(one)

        if 0 < _num <= i:
            break

    fp1.writelines(item_list)

    fp1.close()

    fp.close()
